import React, {useRef, useState} from 'react';

import { Input, Image, Button, message } from 'antd';

import { addBanner } from '../../api/banner';

import { useHistory } from 'react-router';

const Add = () => {

  const [messageApi, messageContent] = message.useMessage()

  const history = useHistory()

  const [link,setLink] = useState()
  const [alt,setAlt] = useState()
  const [img,setImg] = useState()
  const fileRef = useRef()

  return (
    <div>
      添加轮播图
      {messageContent}
      <Input type="text" value={link} onChange={e => setLink(e.target.value)} placeholder='请输入 link' />
      <Input type="text" value={alt}  onChange={e => setAlt(e.target.value)} placeholder='请输入 alt' />
      <input type="file" ref={fileRef} onChange={(event)=>{

          // URL.createObjectURL()

          // 创建一个文件的加载器
          const reader = new FileReader()
          reader.readAsDataURL(event.target.files[0])
          reader.onload = ()=>{
            // 保存图片的 base64
            setImg(reader.result)
          }

      }} hidden />
      <Button style={{backgroundColor: '#89d4f7',color: '#fff'}} onClick={()=>fileRef.current.click()}>选择图片</Button>
      <br />
      <Image src={img} width={100} height={100} />

      <Button onClick={()=>{

        // console.log(link,alt,img);
        if(link && alt && img){
          addBanner({
            link,alt,img
          }).then(res => {
            // console.log(res);
            messageApi.success('添加轮播图成功')
            history.push('/banner/list')
            setLink('')
            setAlt('')
            setImg('')
          })
        }else {
          messageApi.error('链接提示和图片不能为空')
        }
      }}>添加</Button>

    </div>
  );
};

export default Add;
